import { bus } from "@/bus";
import { loadConfig } from '@/config.ts'
import { DataSource, Repository } from "typeorm";
import * as state from '../state'
import { Wristband } from "@/entity/wristband.entity";
import { v4 as uuidv4 } from 'uuid';
// 更新手环表
export async function updateWristband(wbArray: state.WbArray[], wristbandRepo: Repository<Wristband>) {
    // console.log('wbArray', wbArray)
        if (wbArray.length === 0) return;
        // 逐个处理手环，避免竞态条件
        for (const mac of wbArray) {
            let val = {
                fw_name: mac.name,
                fw_version: mac.version,
                time: new Date(),
                deleted: false,
            }
            try {
                // 先尝试更新 - 如果存在则会成功
                const updateResult = await wristbandRepo.update(
                    { mac: mac.addr.toUpperCase() },
                    val
                );
                // console.log('wbArray', val)
                // 如果没有记录被更新，说明手环不存在
                if (updateResult.affected === 0) {
                    // 尝试插入
                    await wristbandRepo.insert({
                        id: uuidv4(),
                        mac: mac.addr.toUpperCase(),
                        time: new Date(),
                        fw_name: mac.name,
                        fw_version: mac.version,
                        deleted: false,
                    });
                }
            } catch (error: any) {
                // 捕获可能的唯一键冲突错误
                if (error.code !== 'ER_DUP_ENTRY' && error.errno !== 1062) {
                    console.error('更新手环时出错:', error);
                    // throw error;
                }
                // 如果是重复键错误，可以忽略，因为这意味着记录已存在
            }
        }
    }